﻿using Newtonsoft.Json;
using NfsCommon.UpoadHepler;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;

namespace ManagerWed.aspx
{
    /// <summary>
    /// FileUpload 的摘要说明
    /// </summary>
    public class FileUpload : UploadHandler
    {
        //返回给UploadyFile的Json结果
        public override string GetResult(string localFileName, string uploadFilePath, string err)
        {
            var result = new
            {
                msg = new
                {
                    localname = localFileName,
                    url = uploadFilePath
                    .Substring(uploadFilePath.IndexOf("\\upload", StringComparison.OrdinalIgnoreCase))
                    .Replace("\\", "/"),
                    date = DateTime.Now.ToShortDateString()
                },
                err = err
            };

            return JsonConvert.SerializeObject(result);
        }

        //即时生成如201323023_s.jpg的缩略图
        public override void OnUploaded(HttpContext context, string filePath)
        {
            //var ext = filePath.Substring(filePath.LastIndexOf('.') + 1).ToLower();
            //if (!ImageExt.Contains(ext))
            //    return;

            //if (string.IsNullOrEmpty(context.Request["thumbs"]))
            //{
            //    this.MakeThumbnail(filePath, "s", context.Request["thumbwidth"].ToInt(85), context.Request["thumbheight"].ToInt(85), string.IsNullOrEmpty(context.Request["mode"]) ? "H" : context.Request["mode"]);
            //}
            //else
            //{
            //    var thumbs = context.Request["thumbs"];
            //    foreach (var thumb in thumbs.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
            //    {
            //        var thumbparts = thumb.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            //        this.MakeThumbnail(filePath, thumbparts[0], thumbparts[1].ToInt(), thumbparts[2].ToInt(), thumbparts[3]);
            //    }
            //}
        }

        private void MakeThumbnail(string filePath, string suffix, int width, int height, string mode)
        {
            string fileExt = filePath.Substring(filePath.LastIndexOf('.'));
            string fileHead = filePath.Substring(0, filePath.LastIndexOf('.'));

            var thumbPath = string.Format("{0}_{1}{2}", fileHead, suffix, fileExt); ;
            //  ThumbnailHelper.MakeThumbnail(filePath, thumbPath, width, height, mode, false);
        }
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="towidth">缩略图指定宽度</param>
        /// <param name="toheight">缩略图指定高度</param>
        public override void MakeThumbnails(string originalImagePath, string thumbnailPath, double towidth, double toheight)
        {
            System.Drawing.Image originalImage = null;
            //新建一个bmp图片
            System.Drawing.Image bitmap = null;

            //新建一个画板
            System.Drawing.Graphics g = null;

            try
            {
                originalImage = System.Drawing.Image.FromFile(originalImagePath);

                double proportion1;
                double proportion2;
                int x = 0;
                int y = 0;
                int ow = originalImage.Width;//原图的宽
                int oh = originalImage.Height;//原图的高
                proportion1 = toheight / Convert.ToDouble(oh);
                proportion2 = towidth / Convert.ToDouble(ow);

                if (toheight > oh && towidth > ow) //如果宽高都小于要缩放的就不缩以与大小缩略
                {
                    toheight = oh;
                    towidth = ow;
                }
                else
                {
                    //根据比例设定相应的高宽
                    if (proportion1 > proportion2)
                    {
                        toheight = proportion2 * originalImage.Height;
                    }
                    else
                    {
                        towidth = proportion1 * originalImage.Width;
                    }
                }

                //新建一个bmp图片
                bitmap = new Bitmap(Convert.ToInt32(towidth), Convert.ToInt32(toheight));

                //新建一个画板
                g = System.Drawing.Graphics.FromImage(bitmap);

                //设置高质量插值法
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                //设置高质量,低速度呈现平滑程度
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //清空画布并以透明背景色填充
                g.Clear(System.Drawing.Color.Transparent);

                //在指定位置并且按指定大小绘制原图片的指定部分
                g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, Convert.ToInt32(towidth), Convert.ToInt32(toheight)),

                new System.Drawing.Rectangle(x, y, ow, oh),
                System.Drawing.GraphicsUnit.Pixel);
                //以jpg格式保存缩略图WebControls
                //File.Delete(thumbnailPath);
                originalImage.Dispose();
                if (!Directory.Exists(thumbnailPath))
                    Directory.CreateDirectory(thumbnailPath);
                string fileExt = originalImagePath.Substring(originalImagePath.LastIndexOf('.'));
                string fileHead = originalImagePath.Substring(0, originalImagePath.LastIndexOf('.'));
                thumbnailPath = string.Format("{0}_{1}{2}", fileHead, "s", fileExt); ;
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png);
            }
            catch (Exception ex)
            {
                string a = ex.Message;
            }
            finally
            {
                try
                {
                    g.Dispose();
                    bitmap.Dispose();
                    originalImage.Dispose();
                }
                catch (Exception ex2)
                {
                    string a = ex2.Message;
                }
            }
        }
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>	
        /// <param name="isaddwatermark">是否添加水印</param>	
        /// <param name="quality">图片品质</param>	
        /// <param name="imagePosition">水印位置</param>	
        /// <param name="waterImage">水印图片名称</param>	
        public override void MakeThumbnailss(string originalImagePath, string thumbnailPath, int width, int height, string mode, bool isaddwatermark = false, int imagePosition = 1, string waterImage = null, int quality = 75)
        {
            Image originalImage = Image.FromFile(originalImagePath);
            string fileExt = originalImagePath.Substring(originalImagePath.LastIndexOf('.'));
            string fileHead = originalImagePath.Substring(0, originalImagePath.LastIndexOf('.'));
            thumbnailPath = string.Format("{0}_{1}{2}", fileHead, "s", fileExt); ;
            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）				
                    break;
                case "W"://指定宽，高按比例					
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）				
                    if (originalImage.Width >= towidth && originalImage.Height >= toheight)
                    {
                        if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                        {
                            oh = originalImage.Height;
                            ow = originalImage.Height * towidth / toheight;
                            y = 0;
                            x = (originalImage.Width - ow) / 2;
                        }
                        else
                        {
                            ow = originalImage.Width;
                            oh = originalImage.Width * height / towidth;
                            x = 0;
                            y = (originalImage.Height - oh) / 2;
                        }
                    }
                    else
                    {
                        x = (originalImage.Width - towidth) / 2;
                        y = (originalImage.Height - toheight) / 2;
                        ow = towidth;
                        oh = toheight;
                    }
                    break;
                case "Fit"://不超出尺寸，比它小就不截了，不留白，大就缩小到最佳尺寸，主要为手机用
                    if (originalImage.Width > towidth && originalImage.Height > toheight)
                    {
                        if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                            toheight = originalImage.Height * width / originalImage.Width;
                        else
                            towidth = originalImage.Width * height / originalImage.Height;
                    }
                    else if (originalImage.Width > towidth)
                    {
                        toheight = originalImage.Height * width / originalImage.Width;
                    }
                    else if (originalImage.Height > toheight)
                    {
                        towidth = originalImage.Width * height / originalImage.Height;
                    }
                    else
                    {
                        towidth = originalImage.Width;
                        toheight = originalImage.Height;
                        ow = towidth;
                        oh = toheight;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片
            Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(Color.White);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                new Rectangle(x, y, ow, oh),
                GraphicsUnit.Pixel);

            //加图片水印
            if (isaddwatermark)
            {
                if (string.IsNullOrEmpty(waterImage))
                    waterImage = "watermarker.png";
                Image copyImage = System.Drawing.Image.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, waterImage));
                //g.DrawImage(copyImage, new Rectangle(bitmap.Width-copyImage.Width, bitmap.Height-copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
                int xPosOfWm;
                int yPosOfWm;
                int wmHeight = copyImage.Height;
                int wmWidth = copyImage.Width;
                int phHeight = toheight;
                int phWidth = towidth;
                switch (imagePosition)
                {

                    default:
                        xPosOfWm = 10;
                        yPosOfWm = 0;
                        break;
                }
                g.DrawImage(copyImage, new Rectangle(xPosOfWm, yPosOfWm, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
            }

            // 以下代码为保存图片时,设置压缩质量
            EncoderParameters encoderParams = new EncoderParameters();
            long[] qualityArray = new long[1];
            qualityArray[0] = quality;
            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityArray);
            encoderParams.Param[0] = encoderParam;
            //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象.
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo jpegICI = null;
            for (int i = 0; i < arrayICI.Length; i++)
            {
                if (arrayICI[i].FormatDescription.Equals("JPEG"))
                {
                    jpegICI = arrayICI[i];
                    //设置JPEG编码
                    break;
                }
            }

            try
            {
                if (jpegICI != null)
                {
                    bitmap.Save(thumbnailPath, jpegICI, encoderParams);
                }
                else
                {
                    //以jpg格式保存缩略图
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
    }
}